#ifndef TCPCOMM_HPP
#define TCPCOMM_HPP

#include "comm_interface.hpp"
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>

class TcpComm : public CommInterface {
public:
    // 客户端模式
    explicit TcpComm(const std::string& ip, unsigned int port);
    
    // 服务器模式
    explicit TcpComm(unsigned int port);
    
    ~TcpComm();
    
    bool initialize() override;
    bool send(const std::vector<uint8_t>& data) override;
    std::vector<uint8_t> receive() override;
    void registerCallback(DataReceivedCallback callback) override;
    std::string getName() const override;
    bool isConnected() const override;
    void shutdown() override;
    
private:
    void readThreadFunc();
    void processReceivedData();
    bool setupSocket();
    bool acceptConnection();
    
    std::string ip_;
    unsigned int port_;
    int server_fd_ = -1;   // 服务器socket
    int client_fd_ = -1;   // 客户端连接socket
    bool is_server_ = false;
    std::atomic<bool> running_{false};
    
    std::thread readThread_;
    std::thread processThread_;
    std::mutex dataMutex_;
    std::condition_variable dataCond_;
    
    std::queue<std::vector<uint8_t>> receiveQueue_;
    
    DataReceivedCallback callback_;
    
    static constexpr size_t BUFFER_SIZE = 4096;
    uint8_t ringBuffer_[BUFFER_SIZE];
    size_t head_ = 0;
    size_t tail_ = 0;
};

#endif // TCPCOMM_HPP